package generadorva;

import ec.util.MersenneTwisterFast;

public class Gamma {
    private double alfa;
    private double beta;

    public Gamma(double a, double b){
        alfa=a;
        beta=1d/b;
    }

    public double generar( MersenneTwisterFast prng){
        double a=1d/Math.sqrt(2*alfa-1);
        double b=alfa-Math.log(4);
        double q=alfa+1d/a;
        double theta=4.5;
        double d=1+Math.log(theta);
        double u1=prng.nextDouble();
        double u2=prng.nextDouble();
        double v=a*Math.log(u1/(1-u1));
        double y=alfa*Math.exp(v);
        double z=u1*u1*u2;
        double w=b+q*v-y;
        while(w+d-theta*z<0){
            if(w>=Math.log(z)){
                return y*beta;
            }else{
            u1=prng.nextDouble();
            u2=prng.nextDouble();
            v=a*Math.log(u1/(1-u1));
            y=alfa*Math.exp(v);
            z=u1*u1*u2;
            w=b+q*v-y;
            }
        }
        return y*beta;
    }

}
